const App = getApp()
import { ShopModel } from '../../models/ShopModel.js'
import { CouponModel } from '../../models/CouponModel.js'
import { AddressModel } from '../../models/AddressModel.js'
import { OrderModel } from '../../models/OrdelModel.js'
import { LoginModel } from '../../models/LoginModel.js'
import Toast from '../../components/dist/toast/toast'
const  Payment  = require('../../utils/payment.js')
let Shop = new ShopModel()
let Coupon = new CouponModel()
let Address = new AddressModel()
let Order = new OrderModel()
let Login = new LoginModel()

Page({
  data: {
    wxlogin: true,
    switch1 : true, //switch开关
    shopInfo:{},//店铺信息
    message:'',//订单备注
    dispatchFee:0,//配送费 默认为0
    packFee:0,//打包费 默认为0
    couponCount:0,// 优惠券可用数量
    coupon:{},//选择使用优惠券
    useCoupon:false,// 是否使用优惠券
    couponId:'', //选中优惠券id
    orderData:{},
    totalPrice:0,
    customerAddress:{},//顾客默认地址
    telephone:'',
    haveAddress:false,
    orderType: "", //订单类型，购物车下单或立即支付下单，默认是购物车，
    pingtuanOpenId: undefined, //拼团的话记录团号
    coupons:false,
    curCoupon: null, // 当前选择使用的优惠券
    curCouponShowText: '请选择使用优惠券', // 当前选择使用的优惠券
    dispatchType: 'selfGet', // 配送方式 kd,zq 分别表示快递/到店自取
    remark: '',
    orderTime:'',
    currentDate: new Date().getHours() + ':' + (new Date().getMinutes() % 10 === 0 ? new Date().getMinutes() : Math.ceil(new Date().getMinutes() / 10) * 10),
    minHour: new Date().getHours(),
    minMinute: new Date().getMinutes(),
    mixHour:22,
    
  },
  async onLoad(options) {
    await this._getCouponInfo()
    await this._getCurrentTime()
    await this._getStorageOrderData()
  },
  async onShow(){
    await this._getShopInfo()
    await this._getSelectdedCoupon()
    await this._getSumPrice()
    await this._getCustomerAddress()
  },
  
  // 计算商品总价 是否使用优惠券
  _getSumPrice:function(){
    console.log('sum',this.data.shopInfo)
    // 原价
    let totalPrice = this.data.orderData.total_price
    // 如果使用优惠券
    if(this.data.useCoupon){
      totalPrice = this._floatSub(totalPrice,this.data.coupon.sub_price) 
    }
    // 如果设置 打包费
   
    if(this.data.shopInfo.pack_fee){
      console.log('打包费')
      totalPrice = this._floatAdd(totalPrice, this.data.shopInfo.pack_fee)
    }
    // 如果设置 配送费
    if(this.data.dispatchType == 'takeOut'){
      if(this.data.shopInfo.dispatch_fee){
        console.log('配送费')
        totalPrice = this._floatAdd(totalPrice, this.data.shopInfo.dispatch_fee)
      }
    }
   
    this.setData({
      totalPrice:totalPrice
    })
  },
  _getOpenId:function(){
    let openId = App.globalData.openId
    this.setData({openId})
    return openId
  },
  // 获取顾客默认地址
  _getCustomerAddress:async function(){
    let address = {
      openId : this._getOpenId(),
      default:true
    }
    let res = await Address.getAddress(address)
    console.log('address',res)
    if(res.length > 0){
      this.setData({
        customerAddress:res[0],
        haveAddress:true
      })
    }
  },
  // 获取缓存中订单信息
  _getStorageOrderData:function(){
    try {
      var orderData = wx.getStorageSync('orderData')
      if (orderData) {
        console.log('orderdata',orderData)
        this.setData({
          orderData:orderData,
          totalPrice:orderData.total_price
        })
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  // 获取店铺信息 ：打包费、配送费、商家地址等信息
  _getShopInfo:async function(){
    let res = await Shop.getShop({})
    console.log('shopinfo',res)
    this.setData({
      shopInfo:res[0],
      mixHour:parseInt(res[0].end_time.slice(0,2))
    })
  },
  // 自定义减法
  _floatSub:function(arg1,arg2){
    var r1,r2,m,n;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
        m=Math.pow(10,Math.max(r1,r2));    
    //动态控制精度长度  
        n=(r1>=r2)?r1:r2;    
    return((arg1*m-arg2*m)/m).toFixed(n);
  } ,
  // 自定义加法
  _floatAdd:function(arg1,arg2){ 
    var r1,r2,m;  
    try{
    　　r1 = arg1.toString().split(".")[1].length;
    }catch(e){r1=0}  try{
    　　r2 = arg2.toString().split(".")[1].length;}catch(e){r2=0}m = Math.pow(10,Math.max(r1,r2));
    return (arg1*m+arg2*m)/m;
  },
  // 输入留言
  inputMessage:function(e){
    this.setData({
      message:e.detail
    })
  },
  inputPhone:function(e){
    this.setData({
      telephone:e.detail
    })
  },
  // 获取用户可用优惠券数量
  _getCouponInfo:async function(){
    let res = await Coupon.getUsefulCoupons()
    this.setData({
      couponCount:res.length
    })
  },
  // 获取选中优惠券信息
  _getSelectdedCoupon:async function(){
    let couponId = this.data.couponId
    if(couponId == ''){
      this.setData({
        coupon:{},
        useCoupon:false
      })
      return
    }
    let coupon = {
      _id : couponId
    }
    if(couponId.length > 0){
      let result = await Coupon.getCoupon(coupon)
      console.log('result',result)
      if(result.length > 0){
        this.setData({
          coupon:result[0],
          useCoupon:true
        })
      }
    }
  },
  // 跳转优惠券页面
  toCoupon:function(){
    wx.navigateTo({
      url: '../selectCoupon/selectCoupon',
    })
  },
 
  // 选择配送模式 自取 外卖
  chioceMode(e){
    const dispatchType = e.currentTarget.dataset.dispatchtype
    this.setData({
      dispatchType
    })
    this.onShow()
    // console.log('dispatchType',dispatchType)
  },

  // 选择收货地址
  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/address/addressList/addressList"
    })
  },

  cancelLogin() {
    wx.navigateBack()
  },
  processLogin(e) {
    if (!e.detail.userInfo) {
      wx.showToast({
        title: '已取消',
        icon: 'none',
      })
      return;
    }
    AUTH.register(this);
  },
  // 门店自取订单 获取手机号
  async getPhoneNumber(e) {
    // 点击 拒绝
    if(e.detail.errMsg !== 'getPhoneNumber:ok'){
      wx.showToast({
        title: '拒绝',
        icon:'none'
      })
      return
    }
    let  cloudID = e.detail.cloudID
    let res = await Login.getTelephone(cloudID)
    let telephone = res.result.data.weRunData.data.phoneNumber
    this.setData({
      telephone
    })
    
  },
  // 获取半小时后的时间
  _getHalfHourTime:function(){
    let date = new Date()
    date.setMinutes(date.getMinutes() + 30)
    let time = date.getHours() + ':' +date.getMinutes()
    return time
  },
  // 初始化配送到达时间 默认半小时后
  _getCurrentTime:function(){
    let currentTime= this._getHalfHourTime()
    this.setData({currentTime})
  },
   // 订单取餐选择时间
  timeChange(e) {
    console.log('time',e)
    this.setData({
      currentTime:e.data
    })
  },
  timeShow() {
    this.setData({
      timeShow: true
    })
  },
  timeHide() {
    this.setData({
      timeShow: false
    })
  },
  timeConfirm(e) {
    console.log('confimr',e.detail)
    this.setData({
      orderTime: e.detail
    })
    this.timeHide()
  },
  // 订单支付
  payGo:async function(orderData, price){
    console.log('paygo')
    let body = orderData.products[0].product_name + '等' + orderData.products.length + '件商品'
    let order = {
      body : body,
      money : price * 100,
  }
  let params = {
      url:'unifiedOrder',
      data:order
  }
  let cloud = await Payment.unifiedOrder(params)
  let pay = await Payment.Pay(cloud.result.data.payment)
  console.log('pay',pay)
  // 如果支付成功
  if(pay){
      // 1、生成新订单
      let res = await Order.createOrder(orderData)
      console.log('createorder',res)
      // 2、删除已使用优惠券（如果使用）
      if(this.data.useCoupon){
        console.log('deleteCoupon')
        await  Coupon.deleteCoupon(this.data.coupon._id)
      }
   }
  },
  // 校验手机号
  isPhoneAvailable:function(poneInput) {
    var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
    if (!myreg.test(poneInput)) {
        return false;
    } else {
        return true;
    }
  },
  // 骑手配送校验
  _checkRider:function(){
    // 1、用户地址是否为空
    if(!this.data.haveAddress){
      return '请先选择地址!'
    }
    if(this.data.currentTime == ''){
      return '请选择订单送达时间!'
    }
    return ''
  },
  // 自取订单校验
  _checkSelfGet:function(){
    let telephone = this.data.telephone
    if(telephone == ''){
      return '请填写联系电话!'
    }
    if(!this.isPhoneAvailable(telephone)){
      return '手机号码填写错误！'
    }
    if(this.data.currentTime == ''){
      return '请选择取餐时间!'
    }
    return ''
  },

  // 提交订单前检查订单信息是否完整
  submit:function(){
    let dispatchType = this.data.dispatchType
    let customerAddress = this.data.customerAddress
    let orderData = this.data.orderData
    //  默认订单状态为已支付，但未发货
    orderData.order_status = 0
    orderData.order_id = new Date().getTime()
    orderData.create_time = new Date()
    orderData.update_time = new Date()
    orderData.arrive_time = this.data.orderTime
    orderData.comment = this.data.message
    orderData.buyer_openid = this.data.openId
    orderData.pay_money = this.data.totalPrice
    orderData.pack_fee = this.data.shopInfo.pack_fee
    if(this.data.useCoupon){
      orderData.coupon_price = this.data.coupon.sub_price
    }

    // 分情况验证
   // 1、骑手配送
    if(dispatchType == 'takeOut'){
      let message = this._checkRider()
      // 有错误提示信息
      if(message.length > 0){
        Toast.fail(message)
      }else{
      // 没有错误提示信息
        orderData.address = customerAddress
        // order_type = 2 为外卖订单
        orderData.order_type = 2
        console.log('orderdata',orderData)
        this.payGo(orderData, this.data.totalPrice)
      }
    }else{
       // 2、用户自取
       let message = this._checkSelfGet()
       // 有错误提示信息
       if(message.length > 0){
         Toast.fail(message)
       }else{
       // 没有错误提示信息
         orderData.customer_telephone = this.data.telephone
         orderData.order_type = 1,
         orderData.shop_address = this.data.shopInfo.detail
         console.log('orderdata',orderData)
         this.payGo(orderData, this.data.totalPrice)
       }

   
    }
  },
})